package com.handler.http.message.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.handler.http.message.model.entity.Account;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author guoQ.z
 * @date 2020/12/29 16:57
 * TODO
 */
@Slf4j
@RestController
@RequestMapping("/practice")
public class PracticeController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("redisLock/{key}/{value}")
    public String method(@PathVariable("key") String key, @PathVariable("value") String value) {
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(key, value, 10L, TimeUnit.SECONDS);
        System.out.println(aBoolean);
        if (aBoolean) {
            System.out.println("execute program......");
        } else {
            System.out.println("obtain lock fail");
        }
        return "";
    }


    public void getList(String keyPattern) {
        Set<String> keys = redisTemplate.keys(keyPattern);
        log.info("key pattern:{}, keys:{}", keyPattern, JSON.toJSONString(keys));
        if (CollectionUtils.isEmpty(keys)) {
            return;
        }
        keys.forEach(key -> {
            List<String> range = redisTemplate.opsForList().range(key, 0, -1);
            if (CollectionUtils.isEmpty(range)) {
                return;
            }
            range.forEach(System.out::println);
        });
    }

    @PostMapping("/testKey")
//    public Object testKey(@RequestBody ModelMap modelMap) {
    public Object testKey(@RequestBody Account account) {
//        return account;
        return Lists.newArrayList();
    }
}
